#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class LRUCache {
    struct Node
    {
        int key, val;
        Node* prev, * next;
        Node() :prev(nullptr), next(nullptr)
        {}
        Node(int _key, int _val) :prev(nullptr), next(nullptr), key(_key), val(_val)
        {}
    };
public:
    LRUCache(int _capacity) :capacity(_capacity), size(0)
    {
        head = new Node();
        tail = new Node();
        head->next = tail;
        tail->prev = head;
    }

    int get(int key) {
        if (!hash.count(key))  return -1;
        Node* node = hash[key];
        removeNode(node);
        addNodeToHead(node);
        return node->val;
    }

    void put(int key, int value) {
        if (hash.count(key))
        {
            Node* node = hash[key];
            node->val = value;
            removeNode(node);
            addNodeToHead(node);
        }
        else
        {
            Node* node = new Node(key, value);
            hash[key] = node;
            addNodeToHead(node);
            if (++size > capacity)
            {
                Node* del = tail->prev;
                removeNode(del);
                hash.erase(del->key);
                delete del;
            }
        }
    }

private:
    void removeNode(Node* node)
    {
        Node* prev = node->prev;
        Node* next = node->next;
        prev->next = next;
        next->prev = prev;
    }

    void addNodeToHead(Node* node)
    {
        Node* headNext = head->next;
        head->next = node;
        node->prev = head;
        node->next = headNext;
        headNext->prev = node;
    }

private:
    Node* head, * tail;
    unordered_map<int, Node*> hash;
    size_t size;
    size_t capacity;
};
